﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Web.Caching;
using System.Web.Mvc;
using CoolCode.Caching;

namespace CoolCode.ServiceModel.Services.Implement {
	public class DbVirtualViewService : IVirtualViewService {
		private static readonly ICache viewCache = new WebCacheStrategy();

		public string[] FileExtensions { get; set; }

		public DbVirtualViewService() {
			FileExtensions = (from v in ViewEngines.Engines
							  let vppv = v as VirtualPathProviderViewEngine
							  where vppv != null
							  select vppv)
							  .SelectMany(c => c.FileExtensions)
							  .ToArray();
		}

		public bool PathExists(string virtualPath) {
			if (!virtualPath.StartsWith("/Views") ||
				!(FileExtensions != null && FileExtensions.Any(ext => virtualPath.EndsWith("." + ext)))) {
				return false;
			}
			var paths = GetViews();

			return paths.Any(c => c.Path == virtualPath);
			/*
			using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultContext"].ConnectionString)) {
				conn.Open();
				var sqlCommand = new SqlCommand(string.Format("select top 1 path from views where path = '{0}' ", virtualPath), conn);

				string v = Convert.ToString(sqlCommand.ExecuteScalar());
				conn.Close();
				return !string.IsNullOrEmpty(v);
			}
			*/
		}

		public IList<VirtualView> GetViews() {
			return viewCache.Get("VirtualViewService-Cache", new SqlCacheDependency("xToDoList", "VirtualViews"),
								 () => {
									 var db = DependencyResolver.Current.GetService<DbContext>();
									 return db.Set<VirtualView>().ToList();
								 });
		}
	}
}
